package com.gpj.learn.rocketmq.base;

import com.gpj.learn.rocketmq.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

/**
 * @className SimpleProducer
 * @description
 *   基本的消息生产者,包含[发送同步消息],[发送异步消息]和[发送单向消息]
 * @author GPJ
 * @date 2021/4/22 21:43
 * @version 1.0
 **/
@Slf4j
public class BaseProducer {
	public static void main(String[] args) throws InterruptedException {
		DefaultMQProducer producer = new DefaultMQProducer("SimpleProducerGroupName");
		producer.setNamesrvAddr(CommonConstants.ROCKETMQ_NAMESERVER_ADDR);
		try {
			producer.start();
			for (int i = 0; i < 10; i++) {
				Message message = new Message("TestTopic", "Tag-A",
						"key:" + UUID.randomUUID().toString(),
						"this is a message".getBytes(RemotingHelper.DEFAULT_CHARSET));
				SendResult result = producer.send(message);
				log.info("消息发送结果{}", result.toString());
			}
		} catch (UnsupportedEncodingException | MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
			e.printStackTrace();
		}finally {
			producer.shutdown();
		}
	}
}
